package com.yy.bolg.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Random;

/**
 * @className: TencentCOSUploadFileUtil.java
 * @methodName: TencentCOSUploadFileUtil
 * @effect: springboot整合腾讯云cos对象储存
 * @author: JingxuanFan
 * @date: 2023/3/14 20:55
 **/
public class TencentCOSUploadFileUtil {
    // 存储桶名称
    private static final String BUCKET_NAME = "wuyang-1331198226";
    //secretId 秘钥id
    private static final String SECRET_ID = "AKID2wkMkvIlDYhfS3XqbDuRp3BoOlCamBRb";
    //SecretKey 秘钥
    private static final String SECRET_KEY = "EKSTQOA4yjO8lQ2u0ypcTK3kMqDQXO3V";
    // 访问域名
    public static final String URL = "https://" + BUCKET_NAME + ".cos.ap-guangzhou.myqcloud.com";
    // 创建COS 凭证
    private static final COSCredentials credentials = new BasicCOSCredentials(SECRET_ID,SECRET_KEY);
    // 配置 COS 区域
    private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));

    /**
     * @methodName uploadfile
     * @effect: 上传文件
     */
    public static String uploadfile(MultipartFile file, String folder){
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials,clientConfig);
        String fileName = file.getOriginalFilename();
        try {
            assert fileName != null;
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),substring);
            file.transferTo(localFile);
            Random random = new Random();
            fileName = folder + random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(BUCKET_NAME, fileName, localFile);
            cosClient.putObject(objectRequest);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            cosClient.shutdown();
        }
        return URL+fileName;
    }
}